package com.swak.boot.config.metrics.telnet;

import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;

import com.swak.annotation.Cmd;
import com.swak.annotation.Server;
import com.swak.boot.booter.ApplicationBooter;
import com.swak.exception.RemotingException;
import com.swak.reactivex.context.EndPoints;
import com.swak.reactivex.context.EndPoints.EndPoint;
import com.swak.registry.URL;
import com.swak.telnet.Telnet;
import com.swak.utils.Sets;

/**
 * 消费者启动
 * 
 * @author lifeng
 */
public class CmdPostProcessor implements BeanPostProcessor, ApplicationBooter {

	private final Set<Object> cmds = Sets.newHashSet();

	/**
	 * 保留EventBus对象
	 */
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	/**
	 * 初始化结束之后注册 -- 只需要找到一个即可
	 */
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		Class<?> clazz = bean.getClass();
		Cmd cmd = clazz.getAnnotation(Cmd.class);
		if (cmd != null) {
			cmds.add(bean);
		}
		return bean;
	}

	/**
	 * 注意： <br>
	 * 1. 如果是服务器环境则需要等待服务器启动之后再初始化其他组件<br>
	 * 2. 如果是应用环境则可以直接启动<br>
	 * 
	 * @param context
	 * @throws RemotingException 
	 */
	@Override
	public void onApplicationEvent(ApplicationContext context) {
		try {
			Telnet.getInstance().start(cmds);
			URL url = Telnet.getInstance().getUrl();
			EndPoint endPoint = new EndPoint();
			endPoint.setHost(url.getHost());
			endPoint.setPort(url.getPort());
			endPoint.setScheme(Server.Telnet);
			EndPoints.me().setEndPoint(endPoint);
		} catch (Exception e) {
		}
	}
}